<?php

namespace App\Exceptions;

use Symfony\Component\HttpFoundation\Response;
use Throwable;
use Illuminate\Http\Request;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param Throwable $e
     * @return void
     *
     * @throws Throwable
     */
    public function report(Throwable $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param Request $request
     * @param Throwable $e
     * @return Response
     *
     * @throws Throwable
     */
    public function render($request, Throwable $e)
    {
        if ($e instanceof ThrottleRequestsException) {
            return response()->json([
                'code' => 1021,
                'message' => '请求太频繁，稍后再试'
            ], 429);
        }

        if ($e instanceof AuthenticationException) {
            return response()->json([
                'message' => $e->getMessage()
            ], 401);
        }

        if ($e instanceof AccessDeniedException) {
            return response()->json([
                'message' => $e->getMessage()
            ], 403);
        }

        if ($e instanceof ValidationException) {
            return response()->json([
                'code' => $e->getCode(),
                'message' => $e->getMessage()
            ], 422);
        }

        return parent::render($request, $e);
    }
}
